package com.example.demo.demo.clone;

import lombok.Data;
import lombok.ToString;

import java.util.Comparator;

@Data
@ToString
public class PhoneNumber implements Cloneable,Comparable<PhoneNumber>, Comparator<PhoneNumber> {
    private short areaCode, prefix, lineNum;
    private String s1, s2, s3;

    public PhoneNumber(short areaCode, short prefix, short lineNum) {
        this.areaCode = areaCode;
        this.prefix = prefix;
        this.lineNum = lineNum;
    }

    public PhoneNumber(String s1, String s2, String s3) {
        this.s1 = s1;
        this.s2 = s2;
        this.s3 = s3;
    }

    @Override
    protected PhoneNumber clone() {
        try {
            return (PhoneNumber) super.clone(); // 适用于类中没有引用的对象，见MyStack类
        } catch (CloneNotSupportedException e) {
            throw new AssertionError();
        }
    }

    public static void main(String[] args) {
        short a = 124;
        short b = 86;
        short c = 34;
        PhoneNumber phoneNumber = new PhoneNumber(a, b, c);
        PhoneNumber clone = phoneNumber.clone();
        System.out.println(clone);

        PhoneNumber phoneNumber2 = new PhoneNumber("a", "b", "c");
        PhoneNumber clone2 = phoneNumber2.clone();
        System.out.println(clone2);

        System.out.println(phoneNumber.hashCode());
    }

    private static final Comparator<PhoneNumber> COMPARATOR = Comparator.comparingInt((PhoneNumber pn) -> pn.areaCode)
            .thenComparingInt(pn -> pn.prefix)
            .thenComparingInt(pn -> pn.lineNum);
    private static final Comparator<PhoneNumber> COMPARATOR2 = new Comparator<PhoneNumber>() { // 等同于COMPARATOR
        @Override
        public int compare(PhoneNumber o1, PhoneNumber o2) {
            int result = o1.areaCode - o2.areaCode;
            if (result == 0) {
                result = o1.prefix - o2.prefix;
                if (result == 0) {
                    result = o1.lineNum - o2.lineNum;
                }
            }
            return result;
        }
    };
    /**
     * 使用比较器
     * @param o
     * @return
     */
    @Override
    public int compareTo(PhoneNumber o) {
        return COMPARATOR.compare(this, o);
    }

    // 或者
//    public int compareTo(PhoneNumber phoneNumber) {
//        int result = Integer.compare(this.areaCode, phoneNumber.areaCode);
//        if (result == 0) {
//            result = Integer.compare(this.prefix, phoneNumber.prefix);
//            if (result == 0) {
//                result = Integer.compare(this.lineNum, phoneNumber.lineNum);
//            }
//        }
//        return result;
//    }

    @Override
    public int compare(PhoneNumber o1, PhoneNumber o2) {
        return 0;
    }
}
